
import { fetchRoomOrders } from '../../../services/api';

Page({
  data: {
    roomId: '',
    orderList: [],
    loading: true,
    intervalId: null, // 定时器ID
  },

  onShow() {
    const roomId = getApp().globalData.roomId || 'DEV_TEST'; // 使用与下单时一致的默认值
    this.setData({ roomId });
    
    // 立即加载一次，然后开启定时刷新
    this.loadOrderData();
    const intervalId = setInterval(() => {
      this.loadOrderData();
    }, 5000); // 每5秒刷新一次
    this.setData({ intervalId });
  },

  onHide() {
    // 页面隐藏时，清除定时器，避免后台刷新消耗资源
    if (this.data.intervalId) {
      clearInterval(this.data.intervalId);
    }
  },

  onUnload() {
    // 页面卸载时，同样清除定时器
    if (this.data.intervalId) {
      clearInterval(this.data.intervalId);
    }
  },

  onPullDownRefresh() {
    this.loadOrderData(() => {
      wx.stopPullDownRefresh();
    });
  },

  loadOrderData(callback) {
    // 首次加载显示loading，后续静默刷新
    if (this.data.loading) {
      this.setData({ loading: true });
    }

    fetchRoomOrders(this.data.roomId).then(res => {
      this.setData({
        orderList: res.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp)), // 按时间倒序
        loading: false,
        showDebugInfo: false, // 数据加载成功，隐藏调试信息
      });
      if (callback) {
        callback();
      }
    }).catch(err => {
      console.error(err);
      this.setData({ loading: false });
      if (callback) {
        callback();
      }
    });
  },

  onViewDetails(e) {
    const { orderid } = e.currentTarget.dataset;
    wx.showToast({ title: `查看订单 ${orderid} 的详情`, icon: 'none' });
  },
});
